#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : lei.wang
from fastcrud import FastCRUD
from app.models import ChatMessages
from app.schemes.chat_messages import ChatMessagesModel, ChatMessagesModels
from app import config

chat_messages_service = FastCRUD(ChatMessages)


class ChatMessagesService:

    @staticmethod
    async def create_chat(db, ask_bazi_question, question, ai_response):
        message = [
            {'role': 'user', 'content': question},
            {'role': 'assistant', 'content': ai_response}
        ]
        chat_message_obj = ChatMessagesModel(
            payload_id=ask_bazi_question,
            message=message,
        )
        return await chat_messages_service.create(db=db, object=chat_message_obj)

    @staticmethod
    async def get_chat_messages(db, payload_id):
        chat_messages_lists = await chat_messages_service.get_multi(
            db=db,
            payload_id=payload_id,
            schema=ChatMessagesModels,
            sort_columns='id',
            sort_orders='asc',
            limit=config.get('chat_round').get('number'),
        )
        return chat_messages_lists

    @staticmethod
    async def get_chat_messages_with_promqt_structure(db, payload_id):
        chat_messages_lists = await chat_messages_service.get_multi(
            db=db,
            payload_id=payload_id,
            schema=ChatMessagesModels,
            sort_columns='id',
            sort_orders='asc',
            limit=config.get('chat_round').get('number'),
        )
        result = []
        for msg in chat_messages_lists.get("data", {}):
            result.extend(msg.get("message", []))
        return result